<template>
	<view class="container">
		<!-- 顶部标题栏 -->
		<view class="header">
			<view class="logo">足球预测</view>
			<!-- <view class="user-avatar" @click="navigateToProfile">{{ userInitial }}</view> -->
		</view>
		
		<!-- 导航标签页 -->
		<view class="nav-tabs">
			<view 
				v-for="(tab, index) in tabs" 
				:key="index" 
				class="nav-tab" 
				:class="{ active: currentTabIndex === index }"
				@click="switchTab(index)"
			>
				{{ tab.name }}
			</view>
		</view>
		
		<!-- 标签页内容 -->
		<view class="tab-content fade-in">
			<!-- 赛事预测标签页 -->
			<view v-if="currentTabIndex === 0">
				<!-- 日期选择器 -->
				<scroll-view scroll-x class="date-tabs" show-scrollbar="false">
					<view 
						v-for="(date, index) in dateTabs" 
						:key="index"
						class="date-tab"
						:class="{ active: currentDateIndex === index, today: date.isToday }"
						@click="switchDate(index)"
					>
						{{ date.label }}
					</view>
				</scroll-view>
				
				<!-- 加载状态 -->
				<view class="loading-state" v-if="isLoading">
					<text>加载中...</text>
				</view>
				
				<!-- 比赛列表 -->
				<view class="matches-container" v-else>
					<match-card 
						v-for="(match, index) in matches" 
						:key="index" 
						:match="match"
						@prediction-change="updatePrediction"
					/>
					
					<view class="empty-state" v-if="matches.length === 0">
						<text>当前日期没有比赛</text>
					</view>
				</view>
			</view>
			
			<!-- 冷门分析标签页 -->
			<view v-if="currentTabIndex === 1">
				<!-- 日期选择器 -->
				<view class="date-selector">
					<view class="date-arrow" @click="changeTrendingDate(-1)">←</view>
					<view class="date-display">{{ trendingDateRange }}</view>
					<view class="date-arrow" @click="changeTrendingDate(1)">→</view>
				</view>
				
				<!-- 冷门分析内容 -->
				<view class="trending-container">
					<trending-card 
						v-for="(match, index) in trendingMatches" 
						:key="index" 
						:match="match"
					/>
					
					<view class="empty-state" v-if="trendingMatches.length === 0">
						<text>待开发</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import MatchCard from '@/components/MatchCard.vue';
import TrendingCard from '@/components/TrendingCard.vue';

export default {
	components: {
		MatchCard,
		TrendingCard
	},
	data() {
		return {
			// 用户信息
			userInfo: null,
			token: '',
			
			// 环境判断
			isMpWeixin: false,
			
			// 标签页
			currentTabIndex: 0,
			tabs: [
				{ name: '赛事预测', id: 'predictions' },
				{ name: '冷门分析', id: 'trending' }
			],
			
			// 日期选择 - 赛事预测
			currentDateIndex: 2, // 默认今天
			dateTabs: [],
			
			// 日期选择 - 冷门分析
			trendingDateOffset: 0,
			trendingDateRange: '',
			
			// 比赛数据
			matches: [],
			
			// 冷门比赛数据
			trendingMatches: [],
			
			// 加载状态
			isLoading: false,
			trendingLoading: false,
			
			// API基础URL
			apiBaseUrl: 'http://127.0.0.1:8000'
		}
	},
	computed: {
		userInitial() {
			return this.userInfo?.name?.substring(0, 1).toUpperCase() || 'U';
		}
	},
	onLoad() {
		console.log('首页onLoad被调用');
		
		// 检查微信小程序环境
		// #ifdef MP-WEIXIN
		this.isMpWeixin = true;
		console.log('当前在微信小程序环境中运行');
		// #endif
		
		// 检查登录状态
		this.checkLoginStatus();
	},
	onShow() {
		console.log('首页onShow被调用');
		// 也在onShow中检查登录状态，以便从其他页面返回时刷新
		this.checkLoginStatus();
	},
	methods: {
		// 检查登录状态
		checkLoginStatus() {
			console.log('检查登录状态...');
			
			// 首先尝试从全局变量获取token
			let token = '';
			let userInfo = null;
			
			// 获取应用实例
			const app = getApp();
			
			// 检查微信小程序环境
			if (this.isMpWeixin && app && app.globalData) {
				console.log('从微信小程序全局数据获取登录信息');
				token = app.globalData.token;
				userInfo = app.globalData.userInfo;
				console.log('全局数据token:', token);
				console.log('全局数据userInfo:', userInfo);
			}
			
			// 如果全局变量中没有，从存储中获取
			if (!token || !userInfo) {
				console.log('尝试从本地存储获取登录信息');
				try {
					token = uni.getStorageSync('token');
					userInfo = uni.getStorageSync('userInfo');
				} catch (e) {
					console.error('获取本地存储失败:', e);
				}
			}
			
			console.log('当前token:', token);
			console.log('当前用户信息:', userInfo);
			
			if (!token || !userInfo) {
				console.warn('未检测到登录状态，准备跳转到登录页');
				
				// 在跳转前尝试清除可能的错误状态
				if (this.isMpWeixin && app) {
					app.globalData = app.globalData || {};
					delete app.globalData.token;
					delete app.globalData.userInfo;
					delete app.globalData.isLoggedIn;
				}
				
				// 未登录，跳转到登录页
				try {
					if (this.isMpWeixin) {
						// 微信环境使用微信API
						wx.redirectTo({
							url: '/pages/login/login',
							fail: (err) => {
								console.error('微信redirectTo登录页失败:', err);
								// 尝试用wx的其他导航方法
								wx.navigateTo({
									url: '/pages/login/login',
									fail: (err2) => {
										console.error('微信navigateTo也失败:', err2);
									}
								});
							}
						});
					} else {
						// 其他环境使用uni API
						uni.redirectTo({
							url: '/pages/login/login',
							success: () => {
								console.log('跳转到登录页成功');
							},
							fail: (err) => {
								console.error('跳转到登录页失败:', err);
								// 尝试其他跳转方式
								uni.navigateTo({
									url: '/pages/login/login',
									fail: (err2) => {
										console.error('navigateTo登录页也失败:', err2);
									}
								});
							}
						});
					}
				} catch (e) {
					console.error('跳转过程异常:', e);
				}
				return;
			}
			
			// 已登录，保存用户信息
			this.token = token;
			this.userInfo = userInfo;
			
			// 确保全局变量中也有token和用户信息
			if (app && app.globalData) {
				app.globalData.token = token;
				app.globalData.userInfo = userInfo;
				app.globalData.isLoggedIn = true;
			}
			
			console.log('登录状态有效，加载数据');
			
			// 初始化数据
			this.initDateTabs();
			this.updateTrendingDateRange();
			this.loadMatchesByDate();
			this.loadTrendingMatches();
		},
		
		// 按日期加载比赛数据
		loadMatchesByDate() {
			if (!this.dateTabs || this.dateTabs.length === 0) return;
			
			const selectedDate = this.dateTabs[this.currentDateIndex].date;
			this.fetchMatchesFromApi(selectedDate);
		},
		
		// 从API获取比赛数据
		fetchMatchesFromApi(date) {
			this.isLoading = true;
			this.matches = []; // 清空现有数据
			
			// 获取token
			let token = this.token;
			
			// 如果没有token, 再次检查全局和存储
			if (!token) {
				const app = getApp();
				if (app && app.globalData && app.globalData.token) {
					token = app.globalData.token;
				} else {
					try {
						token = uni.getStorageSync('token');
					} catch (e) {
						console.error('获取存储token失败:', e);
					}
				}
			}
			
			if (!token) {
				this.handleUnauthenticated();
				return;
			}
			
			// 格式化日期为YYYY-MM-DD格式
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			const formattedDate = `${year}-${month}-${day}`;
			
			const url = `${this.apiBaseUrl}/football/matches?match_time=${formattedDate}`;
			console.log('请求赛事数据URL:', url);
			console.log('认证头:', `Bearer ${token}`);
			
			uni.request({
				url: url,
				method: 'GET',
				header: {
					'accept': 'application/json',
					'Authorization': `Bearer ${token}`
				},
				success: (res) => {
					// console.log('赛事API响应状态码:', res.statusCode);
					// console.log('赛事API返回原始数据:', JSON.stringify(res.data));
					
					if (res.statusCode === 200 && res.data && Array.isArray(res.data)) {
						const formattedData = this.formatMatchData(res.data);
						// console.log('格式化后的比赛数据:', JSON.stringify(formattedData));
						this.matches = formattedData;
					} else if (res.statusCode === 401 || res.statusCode === 403) {
						// token过期或无效
						this.handleUnauthenticated();
					} else if (res.statusCode === 404) {
						// 接口不存在
						console.error('赛事API 404错误，接口可能不存在或URL错误');
						this.showSafeToast('接口不存在，请检查API配置', 'none');
						
						// 临时显示空数据
						this.matches = [];
					} else {
						// 处理其他错误
						console.error('获取比赛数据失败:', res.statusCode, res.data);
						this.showSafeToast(res.data?.detail || res.data?.message || '获取比赛数据失败', 'none');
					}
				},
				fail: (err) => {
					console.error('赛事API请求失败详情:', err);
					
					// 检查具体错误类型
					if (err.errMsg && err.errMsg.includes('404')) {
						this.showSafeToast('赛事接口不存在，请检查API配置', 'none');
					} else {
						this.showSafeToast('网络错误，请稍后重试', 'none');
					}
				},
				complete: () => {
					this.isLoading = false;
				}
			});
		},
		
		// 安全显示Toast消息
		showSafeToast(title, icon = 'none', duration = 2000) {
			// 微信环境下跳过Toast，仅记录日志
			if (this.isMpWeixin) {
				console.log('微信环境跳过Toast:', title);
				return;
			}
			
			try {
				uni.showToast({
					title: title,
					icon: icon,
					duration: duration
				});
			} catch (e) {
				console.error('显示Toast失败:', e, title);
			}
		},
		
		// 加载冷门分析数据
		loadTrendingMatches() {
			this.trendingLoading = true;
			this.trendingMatches = []; // 清空现有数据
			
			// 获取token
			let token = this.token;
			
			// 如果没有token, 再次检查全局和存储
			if (!token) {
				const app = getApp();
				if (app && app.globalData && app.globalData.token) {
					token = app.globalData.token;
				} else {
					try {
						token = uni.getStorageSync('token');
					} catch (e) {
						console.error('获取存储token失败:', e);
					}
				}
			}
			
			if (!token) {
				this.handleUnauthenticated();
				return;
			}
			
			const today = new Date();
			const startDate = new Date(today);
			startDate.setDate(today.getDate() + (this.trendingDateOffset * 7));
			
			const endDate = new Date(startDate);
			endDate.setDate(startDate.getDate() + 6);
			
			// 格式化日期为YYYY-MM-DD格式
			const formatYYYYMMDD = (date) => {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			};
			
			const startDateStr = formatYYYYMMDD(startDate);
			const endDateStr = formatYYYYMMDD(endDate);
			
			const url = `${this.apiBaseUrl}/football/trending?start_date=${startDateStr}&end_date=${endDateStr}`;
			console.log('请求冷门分析URL:', url);
			console.log('认证头:', `Bearer ${token}`);
			
			uni.request({
				url: url,
				method: 'GET',
				header: {
					'accept': 'application/json',
					'Authorization': `Bearer ${token}`
				},
				success: (res) => {
					console.log('冷门分析响应状态码:', res.statusCode);
					console.log('冷门分析API返回数据:', JSON.stringify(res.data));
					
					if (res.statusCode === 200 && res.data && Array.isArray(res.data)) {
						const formattedData = this.formatTrendingData(res.data);
						this.trendingMatches = formattedData;
					} else if (res.statusCode === 401 || res.statusCode === 403) {
						// token过期或无效
						this.handleUnauthenticated();
					} else if (res.statusCode === 404) {
						// 接口不存在
						console.error('冷门分析API 404错误，接口可能不存在或URL错误');
						this.showSafeToast('冷门分析接口不存在', 'none');
						
						// 临时显示空数据
						this.trendingMatches = [];
					} else {
						console.error('获取冷门分析失败:', res.statusCode, res.data);
						this.showSafeToast(res.data?.detail || res.data?.message || '获取冷门分析失败', 'none');
					}
				},
				fail: (err) => {
					console.error('冷门分析API请求失败详情:', err);
					
					// 检查具体错误类型
					if (err.errMsg && err.errMsg.includes('404')) {
						this.showSafeToast('冷门分析接口不存在', 'none');
					} else {
						this.showSafeToast('网络错误，请稍后重试', 'none');
					}
				},
				complete: () => {
					this.trendingLoading = false;
				}
			});
		},
		
		// 格式化API返回的比赛数据
		formatMatchData(apiData) {
			// 直接返回原始API数据，不进行格式化
			console.log('直接使用原始比赛数据');
			return apiData;
		},
		
		// 格式化API返回的冷门分析数据
		formatTrendingData(apiData) {
			// 直接返回原始API数据，不进行格式化
			console.log('直接使用原始冷门分析数据');
			return apiData;
		},
		
		// 从API日期时间格式化为显示格式
		formatApiDateTime(dateTimeStr) {
			if (!dateTimeStr) return '';
			
			try {
				const date = new Date(dateTimeStr);
				const month = date.getMonth() + 1;
				const day = date.getDate();
				const hours = date.getHours();
				const minutes = String(date.getMinutes()).padStart(2, '0');
				
				return `${month}月${day}日 ${hours}:${minutes}`;
			} catch (e) {
				console.error('日期格式化错误:', e);
				return dateTimeStr;
			}
		},
		
		// 获取球队简称 - 不再需要，已移至卡片组件内
		getTeamShortName(teamName) {
			// 此方法已移至卡片组件内
			if (!teamName) return '';
			return teamName.substring(0, 3).toUpperCase();
		},
		
		// 根据预测结果获取推荐类型 - 不再需要，直接使用原始数据
		getPredictionRecommendations(predictionResult) {
			// 此方法不再需要，保留以避免影响现有代码
			return [];
		},
		
		// 处理未授权状态
		handleUnauthenticated() {
			console.log('检测到未授权状态，需要重新登录');
			
			// 清除本地存储的登录信息
			try {
				uni.removeStorageSync('token');
				uni.removeStorageSync('userInfo');
				console.log('已清除登录信息');
				
				// 清除全局变量
				const app = getApp();
				if (app && app.globalData) {
					delete app.globalData.token;
					delete app.globalData.userInfo;
					delete app.globalData.isLoggedIn;
				}
			} catch (e) {
				console.error('清除登录信息失败:', e);
			}
			
			// 安全显示提示 - 使用封装方法
			this.showSafeToast('登录已过期，请重新登录', 'none', 2000);
			
			// 延迟跳转到登录页
			setTimeout(() => {
				console.log('准备跳转到登录页...');
				
				// 使用统一的跳转方式
				uni.reLaunch({
					url: '/pages/login/login',
					success: () => {
						console.log('跳转到登录页成功');
					},
					fail: (err) => {
						console.error('跳转到登录页失败:', err);
						
						// 如果reLaunch失败，尝试redirectTo
						uni.redirectTo({
							url: '/pages/login/login',
							fail: (err2) => {
								console.error('redirectTo也失败了:', err2);
							}
						});
					}
				});
			}, 1000); // 缩短跳转延时
		},
		
		// 切换标签页
		switchTab(index) {
			this.currentTabIndex = index;
		},
		
		// 切换日期
		switchDate(index) {
			this.currentDateIndex = index;
			this.loadMatchesByDate(); // 切换日期后重新加载数据
		},
		
		
		// 初始化日期选择器
		initDateTabs() {
			const today = new Date();
			this.dateTabs = Array.from({ length: 7 }, (_, i) => {
				const date = new Date(today);
				date.setDate(today.getDate() + (i - 2)); // 从前天到未来4天
				
				const isToday = i === 2;
				const month = date.getMonth() + 1;
				const day = date.getDate();
				
				const label = `${month}月${day}日`;
				
				console.log(`创建日期标签: ${label}, 日期: ${date.toLocaleDateString()}`);
				
				return {
					date: date,
					label: label,
					isToday
				};
			});
		},
		
		// 比较日期（仅年月日）
		formatDateForCompare(date) {
			return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
		},
		
		// 冷门分析日期范围
		changeTrendingDate(offset) {
			this.trendingDateOffset += offset;
			this.updateTrendingDateRange();
			this.loadTrendingMatches(); // 重新加载冷门分析数据
		},
		
		updateTrendingDateRange() {
			const today = new Date();
			const startDate = new Date();
			startDate.setDate(today.getDate() + (this.trendingDateOffset * 7));
			
			const endDate = new Date(startDate);
			endDate.setDate(startDate.getDate() + 6);
			
			this.trendingDateRange = `${this.formatDate(startDate)} - ${this.formatDate(endDate)}`;
		},
		
		// 日期格式化
		formatDate(date) {
			const year = date.getFullYear();
			const month = date.getMonth() + 1;
			const day = date.getDate();
			return `${year}年${month}月${day}日`;
		},
		
		// 跳转到个人中心页面
		navigateToProfile() {
			uni.switchTab({
				url: '/pages/profile/profile'
			});
		},
		
		// 退出登录
		logout() {
			uni.showModal({
				title: '提示',
				content: '确定要退出登录吗？',
				success: (res) => {
					if (res.confirm) {
						// 清除登录信息
						uni.removeStorageSync('token');
						uni.removeStorageSync('userInfo');
						
						// 跳转到登录页
						uni.redirectTo({
							url: '/pages/login/login'
						});
					}
				}
			});
		}
	}
}
</script>

<style lang="scss">
	.container {
		padding: $spacing-lg;
		max-width: 960rpx;
		margin: 0 auto;
		min-height: 100vh;
		background-color: #f9f9fb;
	}

	/* 顶部标题栏 */
	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: $spacing-base 0;
		margin-bottom: $spacing-lg;
		border-bottom: 2rpx solid rgba(0, 0, 0, 0.05);
	}

	.logo {
		font-size: $font-size-xl;
		font-weight: 700;
		color: $primary;
		letter-spacing: 1rpx;
		position: relative;
		
		&::after {
			content: '';
			position: absolute;
			left: 0;
			bottom: -6rpx;
			width: 40%;
			height: 4rpx;
			background: linear-gradient(90deg, $primary, transparent);
			border-radius: 4rpx;
		}
	}

	.user-avatar {
		width: 72rpx;
		height: 72rpx;
		border-radius: $avatar-radius;
		background: linear-gradient(135deg, $primary 0%, darken($primary, 15%) 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		color: $light;
		font-weight: bold;
		font-size: $font-size-lg;
		box-shadow: 0 4rpx 12rpx rgba(58, 134, 255, 0.2);
		transition: all 0.3s ease;
		
		&:active {
			transform: scale(0.95);
			box-shadow: 0 2rpx 8rpx rgba(58, 134, 255, 0.15);
		}
	}

	/* 导航标签页 */
	.nav-tabs {
		display: flex;
		margin-bottom: $spacing-base;
		border-bottom: 2rpx solid rgba(0, 0, 0, 0.05);
		position: relative;
	}

	.nav-tab {
		padding: $spacing-sm $spacing-base;
		margin-right: $spacing-sm;
		font-weight: 500;
		color: $text-color-secondary;
		border-bottom: 4rpx solid transparent;
		transition: all $transition-speed;
		position: relative;
		text-align: center;
		
		&::after {
			content: '';
			position: absolute;
			bottom: -4rpx;
			left: 50%;
			transform: translateX(-50%) scaleX(0);
			width: 60%;
			height: 4rpx;
			background-color: $primary;
			border-radius: 4rpx;
			transition: transform 0.3s ease;
		}
		
		&.active {
			color: $primary;
			font-weight: 600;
			
			&::after {
				transform: translateX(-50%) scaleX(1);
			}
		}
	}

	/* 日期选择器 */
	.date-tabs {
		display: flex;
		white-space: nowrap;
		margin-bottom: $spacing-base;
		padding-bottom: $spacing-xs;
	}

	.date-tab {
		display: inline-block;
		padding: $spacing-xs $spacing-base;
		margin-right: $spacing-xs;
		border-radius: 40rpx;
		background-color: rgba(0, 0, 0, 0.03);
		color: $text-color-secondary;
		font-size: $font-size-sm;
		transition: all 0.3s ease;
		border: 2rpx solid transparent;
		
		&.active {
			background-color: $primary;
			color: $light;
			box-shadow: 0 4rpx 12rpx rgba(58, 134, 255, 0.2);
		}
		
		&.today {
			border: 2rpx solid $primary;
		}
		
		&:active {
			transform: scale(0.95);
		}
	}

	.date-selector {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: $spacing-base;
		padding: 0 $spacing-sm;
	}

	.date-arrow {
		width: 60rpx;
		height: 60rpx;
		border-radius: 30rpx;
		background-color: $light;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		font-weight: bold;
		color: $text-color;
		transition: all 0.3s ease;
		
		&:active {
			transform: scale(0.9);
			box-shadow: 0 1rpx 5rpx rgba(0, 0, 0, 0.1);
		}
	}

	.date-display {
		font-size: $font-size-sm;
		color: $text-color-secondary;
		background-color: rgba(0, 0, 0, 0.02);
		padding: 8rpx 20rpx;
		border-radius: 30rpx;
		font-weight: 500;
	}

	/* 加载状态 */
	.loading-state, .empty-state {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: $spacing-xl 0;
		color: $text-color-secondary;
		font-size: $font-size-sm;
		background-color: rgba(0, 0, 0, 0.02);
		border-radius: 8rpx;
		margin: $spacing-lg 0;
		min-height: 300rpx;
	}
	
	/* 渐变动画 */
	.fade-in {
		animation: fadeIn 0.5s ease-in-out;
	}
	
	@keyframes fadeIn {
		from {
			opacity: 0;
			transform: translateY(10rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
	
	/* 比赛容器 */
	.matches-container, .trending-container {
		padding: 0 $spacing-xs;
	}
</style>
